package com.bhs.sansonglogistics.ui.quality;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.DedicatedLineBean;
import com.bhs.sansonglogistics.bean.DedicatedLineDataBean;
import com.bhs.sansonglogistics.bean.PictureBean;
import com.bhs.sansonglogistics.bean.QualityVoucherData;
import com.bhs.sansonglogistics.bean.VoucherListBean;
import com.bhs.sansonglogistics.net.Config;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.other.WebViewActivity;
import com.bhs.sansonglogistics.ui.wallet.SuccessfullyAddedActivity;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;

import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 押金退还
 */
public class RefundActivity extends BaseActivity implements View.OnClickListener, NetCallBack {

    private RecyclerView mRvList;
    private CheckBox mCbAll;
    private Button mBtnSubmit;
    private BaseQuickAdapter<VoucherListBean.DataDTO.ListDTO, BaseViewHolder> mAdapter;
    //	退押金开关：0=关，1=开
    private int RefundSwitch;
    private TextView mTvHint;
    private final String serviceTel = "4008899050";

    @Override
    public int initLayout() {
        return R.layout.activity_refund;
    }

    @Override
    public void initView() {
        RefundSwitch = getIntent().getIntExtra("Switch", 0);
        TextView mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("申请退还");
        mRvList = findViewById(R.id.rv_list);
        mCbAll = findViewById(R.id.cb_all);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnSubmit.setOnClickListener(this);
        mTvHint = findViewById(R.id.tv_hint);
        if (RefundSwitch == 0){
            mTvHint.setVisibility(View.VISIBLE);
            mBtnSubmit.setEnabled(false);
            mBtnSubmit.setBackgroundColor(Color.parseColor("#7F485EF4"));
        } else{
            mTvHint.setVisibility(View.GONE);
        }
    }

    @Override
    public void initData() {
        mAdapter = new BaseQuickAdapter<VoucherListBean.DataDTO.ListDTO, BaseViewHolder>(R.layout.item_refund_line) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, VoucherListBean.DataDTO.ListDTO item) {
                helper.setText(R.id.tv_start_city, item.getLine_name());
                // helper.setText(R.id.tv_end_city, item.getEnd_city());
                helper.setText(R.id.tv_money, String.format("%s元", item.getMoney()));
                helper.setImageResource(R.id.iv_checked, item.isChecked() ? R.mipmap.ic_checked : R.mipmap.ic_unchecked);
            }
        };
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(mActivity));
        Map<String, String> map = new ArrayMap<>();
        map.put("page", "1");
        map.put("limit", "1000");
        map.put("refund_status", "0,4");
        networkRequest(netApi.deposit_list(map), this, 666);
        mAdapter.setEmptyView(LayoutInflater.from(mActivity).inflate(R.layout.layout_empty, null));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                VoucherListBean.DataDTO.ListDTO data = mAdapter.getData().get(position);
                data.setChecked(!data.isChecked());
                mAdapter.notifyDataSetChanged();
            }
        });

        mCbAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                for (VoucherListBean.DataDTO.ListDTO datum : mAdapter.getData()) {
                    datum.setChecked(b);
                }
                mAdapter.notifyDataSetChanged();
            }
        });

        String str = "退还押金渠道已关闭，如有疑问请联系平台客服";
        SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(str);
        ClickableSpan clickableSpanOne = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                MyUtils.callPhone(mActivity, serviceTel);
            }

            @Override
            public void updateDrawState(TextPaint paint) {
                paint.setColor(Color.parseColor("#485EF4"));
                // 设置下划线 true显示、false不显示
                paint.setUnderlineText(false);
            }
        };

        spannableBuilder.setSpan(clickableSpanOne, 17, 21, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvHint.setMovementMethod(LinkMovementMethod.getInstance());
        mTvHint.setText(spannableBuilder);
    }

    @Override
    public void onClick(View view) {

        StringBuilder images = new StringBuilder();
        for (VoucherListBean.DataDTO.ListDTO datum : mAdapter.getData()) {
            if (datum.isChecked()) {
                images.append(datum.getId()).append(",");
            }
        }
        if (!TextUtils.isEmpty(images)) {
            images = new StringBuilder(images.substring(0, images.toString().lastIndexOf(",")));
        }
        if (TextUtils.isEmpty(images)) {
            ToastUtil.show("请选择你要退款的专线");
            return;
        }
        loadingPopupShow();
        networkRequest(netApi.refund_deposit_order( images.toString()), this, 11);
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 666) {
            VoucherListBean bean = new Gson().fromJson(json, VoucherListBean.class);
            if (bean.isStatus()) {
                mAdapter.setNewData(bean.getData().getList());
            }
        } else if (requestCode == 11) {
            loadingPopupDismiss();
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            if (bean.isStatus()) {
                startActivity(new Intent(mActivity, SuccessfullyAddedActivity.class)
                        .putExtra("type", 1));
                finish();
            } else {
                ToastUtil.show(bean.getMsg());
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }
}